package com.wynn.service.impl;

import com.wynn.dao.OrderDao;
import com.wynn.dao.ProductDao;
import com.wynn.pojo.Order;
import com.wynn.pojo.OrderException;
import com.wynn.pojo.Product;
import com.wynn.pojo.Result;
import com.wynn.service.OrderService;
import com.wynn.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Transactional
@RestController
@RequestMapping("order")
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ProductDao productDao;

    @Override
    @GetMapping("statisticExc")
    public Result statisticExc() {

        Result result = new Result();
        try {
            //查询当前季度异常订单数量
            int sum = orderDao.statisticByStatus("-1");
            result.setData(sum);
            result.setCode("200");
        }catch (Exception e){
            result.setCode("503");
            result.setMessage("统计异常订单失败");
            log.warn("统计订单状态失败");
        }

        return result;
    }

    @Override
    @GetMapping("statisticNum")
    public Result statisticOrder() {
        Result result = new Result();
        try {
            //查询当前季度所有订单
            int sum = orderDao.statisticAll();
            result.setData(sum);
            result.setCode("200");
        }catch (Exception e){
            result.setCode("503");
            result.setMessage("统计订单失败");
        }

        return result;
    }

    @Override
    @GetMapping("statisticDone")
    public Result statisticDone() {
        Result result = new Result();
        try {
            //查询当前季度完成订单数量
            int sum = orderDao.statisticByStatus("1");
            result.setData(sum);
            result.setCode("200");

        }catch (Exception e){
            result.setCode("503");
            result.setMessage("统计完成订单异常");
        }

        return result;
    }

    @Override
    @GetMapping("getChartData2")
    public Result getChartData2() {
        Result result = new Result();
        //加载自当月起，6个月以来的订单需求
        HashMap<String, Object> data = new HashMap<>();
        try {
            //获取当前年份
            int year = DateUtils.getCurrentYear();
            //获取当前月份
            int month = DateUtils.getCurrentMonth();
            List<String> labels=new ArrayList<>();
            //加载横坐标
            for (int i =  month-5; i <= month; i++) {
                if (i <= 0){
                    labels.add(year-1+"-"+(i+12));
                }else {
                    if (i<10){
                        labels.add(year+"-0"+i);
                    }else {
                        labels.add(year+"-"+i);
                    }

                }
            }
            data.put("labels",labels);
            //查询所有的产品
            List<Product> productList = productDao.findAllProduct();
            ArrayList<Object> datasets = new ArrayList<>();
            for (Product product : productList) {
                int[] productNum = new int[6];

                HashMap<String, Object> dataset = new HashMap<>();
                dataset.put("label",product.getProductName());
                for (int i = 0; i < 6; i++) {
                    //查询某月某产品的数量
                    productNum[i] = orderDao.queryNumPidAndMonth(product.getId(),labels.get(i));
                }
                dataset.put("data",productNum);
                datasets.add(dataset);
            }
            data.put("datasets",datasets);
            result.setCode("200");
            result.setData(data);
        }catch (Exception e){
            result.setCode("503");
            result.setMessage("图标二数据获取失败");
        }

        return result;
    }

    @Override
    @GetMapping("searchAll")
    public List<Order> searchAll(String deadLine, String company, Integer product) throws ParseException {
        Date date = null;
        if (deadLine!=null){
            date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(deadLine);
            date =DateUtils.dateAdd1(date);
        }
        if (company.equals("")){
            company=null;
        }

        List<Order> orders = orderDao.searchAll(date,company,product);
        return orders;
    }

    @Override
    @GetMapping("deleteOrder")
    public void deleteOrder(int id) {
        orderDao.deleteOrderExcByOid(id);
        orderDao.deleteOrderById(id);
    }

    @Override
    @PostMapping("addOrder")
    public void addOrder(@RequestBody Order order) {
        orderDao.addOrder(order);
    }

    @Override
    @PostMapping("editOrder")
    public void editOrder(@RequestBody Order order) {
        Date createDate = order.getCreateDate();
        Date deadLine = order.getDeadLine();
        if(createDate==null){
            createDate = DateUtils.dateAdd1(createDate);
            order.setCreateDate(createDate);
        }

        if (deadLine==null){
            deadLine = DateUtils.dateAdd1(deadLine);
            order.setDeadLine(deadLine);
        }
        orderDao.editOrder(order);
    }

    @Override
    @PostMapping("addOrderException")
    public boolean addOrderException(@RequestBody Map<String,String> orderException) {
        int orderId = Integer.parseInt(orderException.get("orderId"));//发生异常得订单id
        //判断该订单是否已经设为异常
        Order exitOrder = orderDao.findById(orderId);

        if(exitOrder.getStatus().equals("-1")){
            return false;//该订单已经设为异常
        }

        OrderException exception = new OrderException();
        String describe=orderException.get("describe");

        //获取上报时间
        Date date = new Date();
        Order order = new Order();
        order.setId(orderId);
        //异常记录
        exception.setContent(describe);
        exception.setOrder(order);
        exception.setReportTime(date);
        exception.setStatus(0);
        //添加订单异常记录
        orderDao.addOrderException(exception);
        //将订单状态改为异常
        orderDao.updateOrderStu(orderId,"-1");
        return true;
    }

    @Override
    @PostMapping("submit")
    public void submit(@RequestBody Order order) {
        orderDao.updateOrderStu(order.getId(),"1");
    }

    @Override
    @PostMapping("searchException")
    public List<OrderException> searchException(@RequestBody Map<String, String> map) throws ParseException {
        String sdeadLine = map.get("deadLine");
        String company = map.get("company");
        String sstatus = map.get("status");

        int status=-1;
        //默认是null
        Date deadLine=null;
        if (sdeadLine!=null){
            deadLine=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(sdeadLine);
            deadLine=DateUtils.dateAdd1(deadLine);
        }
        if (company.equals("")){
            company=null;
        }
        if (sstatus!=null){
            status = Integer.parseInt(sstatus);
        }

        List<OrderException> orderExceptions =  orderDao.searchException(deadLine,company,status);
        return orderExceptions;
    }

    @Override
    @PostMapping("editException")
    public void editException(@RequestBody OrderException orderException) {
        orderDao.editException(orderException);
    }

    @Override
    @GetMapping("recoverException")
    public void recoverException(int id,int orderId) {
        orderDao.updateOrderStu(orderId,"0");
        orderDao.updateOrderExceptionStu(id,1);
    }


    @GetMapping("selectAll")
    public List<Order> selectAll(){
        return orderDao.selectAll();
    }

}
